using System;
using OTE.Domain;
using OTE.Tasks.Commands.Question;
using SharpArch.Domain.Commands;
using SharpArch.NHibernate.Contracts.Repositories;

namespace OTE.Tasks.CommandHandlers.Question
{
    public class QuestionMetaDataAddedHandler : ICommandHandler<QuestionMetaDataAddedCommand>
    {
        private readonly INHibernateRepository<User> _userRepository;
        private readonly INHibernateRepository<Domain.Category> _categoryRepository;
        private readonly INHibernateRepository<Domain.Question> _questionRepository;

        public QuestionMetaDataAddedHandler(INHibernateRepository<Domain.Category> categoryRepository, INHibernateRepository<User> userRepository, INHibernateRepository<Domain.Question> questionRepository)
        {
            _categoryRepository = categoryRepository;
            _userRepository = userRepository;
            _questionRepository = questionRepository;
        }

        public ICommandResult Handle(QuestionMetaDataAddedCommand command)
        {
            var category = _categoryRepository.Get(command.CategoryId);

            var user = _userRepository.Get(command.UserId);

            var question = new Domain.Question()
                               {
                                   Category = category,
                                   User = user,
                                   Content = command.Content,
                                   CreatedBy = command.CreatedBy,
                                   CreatedDate = DateTime.Now,
                                   ModifiedDate = DateTime.Now,
                                   ModifiedBy = command.CreatedBy
                               };

            var ques = _questionRepository.Save(question);

            var result = ques == null
                ? new QuestionMetaDataAddedResult(false)
                : new QuestionMetaDataAddedResult(true) { Question = ques };

            return result;
        }
    }
}